package com.sky.aspect;

import com.sky.annotion.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.entity.Category;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.naming.Context;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {
    /**
     * 切点表达式
     */
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotion.AutoFill)")
    public void autoFillPointCut(){

    }
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    log.info("公共字段填充开始... ...{}",joinPoint);
//    获取当前被拦截方法上的操作类型
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();//方法签名对象
    AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);//获取方法上的注解
    OperationType operationType = autoFill.value();//获取事先定义好的类型
    log.info("当前执行方法为{}类型",operationType);

//    获取当前被拦截方法上的实体对象
    Object[] entrys = joinPoint.getArgs();
    if (entrys == null || entrys.length == 0){
        return;
    }
    Object entry = entrys[0];
//      为赋值操作提供数据
        LocalDateTime dateTime = LocalDateTime.now();
        Long currentUser = BaseContext.getCurrentId();

        Method setUpdateUser = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,Long.class);
        Method setCreateUser = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER,Long.class);
        Method setCreateTime = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME,LocalDateTime.class);
        Method setUpdateTime = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class);
    if (operationType == OperationType.INSERT){
        setCreateUser.invoke(entry,currentUser);
        setUpdateTime.invoke(entry,dateTime);
        setCreateTime.invoke(entry,dateTime);
        setUpdateUser.invoke(entry,currentUser);

    } else if (operationType == OperationType.UPDATE) {
        setUpdateTime.invoke(entry,dateTime);
        setUpdateUser.invoke(entry,currentUser);
    }
  }
}
